# -*- coding=utf-8 -*-

import MySQLdb
from MySQLdb import escape_string
import pymongo

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

def getfile(type):
    f = open(type + ".txt")
    return f

conn= MySQLdb.connect(
    host='127.0.0.1',
    port = 3306,
    user='root',
    passwd='',
    db ='drug',
)
cur = conn.cursor()


mongodb = pymongo.MongoClient("mongodb://175.102.18.112:27018").OpenCollege.all_courses


resultType = "30"
#插入一条数据
f = open(resultType +  ".txt")
lines = f.readlines()

for line in lines:
    if line != u"\n":
        lineValueArr = line.split(" ")
        if len(lineValueArr) > 1:
            keywords = lineValueArr[0]
            keyValue = lineValueArr[3]
            keyType = resultType
            wordCount = mongodb.find({"html":{"$regex":keywords}}).count()
            insertSQL = "insert into results(keywords,keyValue,keyType,wordCount) VALUES ('%s','%s','%s','%s')"% (keywords, keyValue, keyType, str(wordCount))
            cur.execute(insertSQL)
        else:
            print u"分割line失败"
    else:
        print u"本行内容为空"
    #修改查询条件的数据
    #cur.execute("update student set class='3 year 1 class' where name = 'Tom'")

    #删除查询条件的数据
    #cur.execute("delete from student where age='9'")

    conn.commit()
f.close()
cur.close()
conn.close()
